function goodMood(msg){
    layer.alert(msg, {icon: 6,time:3000});
}

function badMood(msg){
    layer.alert(msg, {icon: 5,time:3000});
}

function toAddData(isAdd){
    var flag = $("#addBtn").attr("data");
    if (flag==1){
        var name;
        var uuid;
        if (isAdd){
            name = $('#myModal_1').find("input[name='name']").val();
        }else {
            name = $('#myModal_3').find("input[name='name']").val();
            uuid = $('#myModal_3').find("input[name='uuid']").val();
        }
        $.ajax({
            type : "post",
            url : ctx+"/addOrEditData",
            async : false,//同步请求
            data:{flag:1,name:name,isAdd:isAdd,uuid:uuid},
            dataType:"text",
            success : function(data){
                if (isAdd){
                    $('#myModal_1').modal('hide');
                }else {
                    $('#myModal_3').modal('hide');
                }
                $("#node_1").trigger("click");
            },
            error : function(e){
                badMood("操作失败！");
            }
        });

    }else if (flag==2){
        var ip;
        var port;
        var cluster;
        var uuid;
        if (isAdd){
            ip = $('#myModal_2').find("input[name='ip']").val();
            port = $('#myModal_2').find("input[name='port']").val();
            cluster = $('#myModal_2').find("select[name='cluster']").val();
        }else {
            uuid = $('#myModal_4').find("input[name='uuid']").val();
            ip = $('#myModal_4').find("input[name='ip']").val();
            port = $('#myModal_4').find("input[name='port']").val();
            cluster = $('#myModal_4').find("select[name='cluster']").val();
        }
        $.ajax({
            type : "post",
            url : ctx+"/addOrEditData",
            async : false,//同步请求
            data:{flag:2,ip:ip,port:port,cluster:cluster,isAdd:isAdd,uuid:uuid},
            dataType:"text",
            success : function(data){
                if (isAdd){
                    $('#myModal_2').modal('hide');
                }else {
                    $('#myModal_4').modal('hide');
                }
                $("#node_2").trigger("click");
            },
            error : function(e){
                badMood("操作失败！");
            }
        });
    }
}

$(function(){
    $('#myModal_1').on('show.bs.modal', function (e) {
        $("input[name='name']").val("");
    })
    $('#myModal_2').on('show.bs.modal', function (e) {
        $("input[name='ip']").val("");
        $("input[name='port']").val("");
        $.ajax({
            type : "post",
            url : ctx+"/clusterData",
            async : false,//同步请求
            dataType:"json",
            success : function(data){
                var html = "";
                var len = data.length;
                for (var i=0;i < len;i++){
                    html += '<option value="'+data[i].uuid+'">'+data[i].name+'</option>';
                }
                $("#cluster").html(html);
            }
        });
    })
});


function delData(type,uuid){
    $.ajax({
        type : "post",
        url : ctx+"/delData",
        async : false,//同步请求
        data:{flag:type,uuid:uuid},
        dataType:"text",
        success : function(data){
            if (type==1){
                if (data=="false"){
                    badMood("集群中有节点，不允许删除！");
                }else {
                    $("#node_1").trigger("click");
                }
            }else if (type==2){
                $("#node_2").trigger("click");
            }
        },
        error : function(e){
            alert("操作失败！");
            badMood("操作失败！");
        }
    });
}
function editData(type,uuid){
    var obj;
    $.ajax({
        type : "post",
        url : ctx+"/getData",
        async : false,//同步请求
        data:{type:type,uuid:uuid},
        dataType:"json",
        success : function(data){
            obj = data;
        }
    });
    if (type==1){
        $('#myModal_3').find("input[name='uuid']").val(obj.uuid);
        $('#myModal_3').find("input[name='name']").val(obj.name);
        $('#myModal_3').modal('show');
    }else if (type){
        $('#myModal_4').find("input[name='uuid']").val(obj.uuid);
        $('#myModal_4').find("input[name='ip']").val(obj.ip);
        $('#myModal_4').find("input[name='port']").val(obj.port);
        $.ajax({
            type : "post",
            url : ctx+"/clusterData",
            async : false,//同步请求
            dataType:"json",
            success : function(data){
                var html = "";
                var len = data.length;
                for (var i=0;i < len;i++){
                    if (data[i].uuid==obj.cluster_id){
                        html += '<option value="'+data[i].uuid+'" selected="selected">'+data[i].name+'</option>';
                    }else {
                        html += '<option value="'+data[i].uuid+'">'+data[i].name+'</option>';
                    }
                }
                $('#myModal_4').find("select[name='cluster']").html(html);
            }
        });
        $('#myModal_4').modal('show');
    }
}


function delServer(clusterId,uuid){
    $.ajax({
        type : "post",
        url : ctx+"/delData",
        async : false,//同步请求
        data:{flag:2,uuid:uuid},
        dataType:"text",
        success : function(data){
            viewData(null,clusterId);
        },
        error : function(e){
            alert("操作失败！");
            badMood("操作失败！");
        }
    });
}


function viewData(who,uuid){
    var count;
    if(who!=null){
        count = $(who).parent().prev().html();
        var title = $(who).parent().prev().prev().html();
        $("#myModalLabel_5").html("["+title+"] 节点查看");
    }
    if (count==0){
        badMood("集群节点为 0 ！");
    }else {
        $.ajax({
            type : "post",
            url : ctx+"/getServerByClusterId",
            async : false,//同步请求
            data:{uuid:uuid},
            dataType:"json",
            success : function(dataList){
                $("#serverData").html("");
                if (dataList.length==0){
                    $('#myModal_5').modal('hide');
                    $("#node_1").trigger("click");
                    return;
                }else {
                    var html = "";
                    for (var j=0;j<dataList.length;j++){
                        var data = dataList[j];
                        html += '<div class="row" style="margin-top: 20px!important;">';
                        for (var i=0;i<data.length;i++){
                            html += '<div class="col-md-4">';
                            html += '<button ondblclick="delServer(';
                            html +=  "'" +uuid + "'" + "," + "'" +data[i].uuid + "'" + ");" + "\"";
                            html +=  ' class="btn btn-success">'+data[i].ip+':'+data[i].port+'</button>';
                            html += '</div>';
                        }
                        html += '</div>';
                    }
                    $("#serverData").html(html);
                    $('#myModal_5').modal('show');
                }
            }
        });
    }
}


function clusterData(){
    $.ajax({
        type : "post",
        url : ctx+"/clusterData",
        async : false,//同步请求
        dataType:"json",
        success : function(data){
            var html = '<tr><th style="width:5%">序号</th><th>集群名称</th><th>集群大小</th><th>操作</th></tr>';
            if (data.length==0){
                html += '<tr><td colspan="4">无数据，请添加。</td></tr>';
            }else {
                for (var i=0;i < data.length;i++){
                    html += '<tr><td>'+(i+1)+'</td><td>'+data[i].name+'</td><td>'+data[i].count+'</td>';
                    html += '<td><button class="btn btn-sm btn-danger" onclick="delData(1,\''+data[i].uuid+'\')">删除</button>&nbsp;&nbsp;&nbsp;' +
                        '<button class="btn btn-sm btn-info" onclick="editData(1,\''+data[i].uuid+'\')">修改</button>&nbsp;&nbsp;&nbsp;' +
                        '<button class="btn btn-sm btn-success" onclick="viewData(this,\''+data[i].uuid+'\')">查看</button></td>';
                    html += '</tr>';
                }
            }
            $("#table").html(html);
        }
    });
    $("#addBtn").attr("data",1);
    $("#addBtn").attr("data-target","#myModal_1");
}


function serverData(){
    $.ajax({
        type : "post",
        url : ctx+"/serverData",
        async : false,//同步请求
        dataType:"json",
        success : function(data){
            var html = '<tr><th style="width:5%">序号</th><th>服务IP</th><th>服务端口</th><th>操作</th></tr>';
            if (data.length==0){
                html += '<tr><td colspan="4">无数据，请添加。</td></tr>';
            }else {
                for (var i=0;i < data.length;i++){
                    html += '<tr><td>'+(i+1)+'</td><td>'+data[i].ip+'</td><td>'+data[i].port+'</td>';
                    html += '<td><button class="btn btn-sm btn-danger" onclick="delData(2,\''+data[i].uuid+'\')">删除</button>&nbsp;&nbsp;&nbsp;' +
                        '<button class="btn btn-sm btn-info" onclick="editData(2,\''+data[i].uuid+'\')">修改</button></td>';
                    html += '</tr>';
                }
            }
            $("#table").html(html);
        }
    });
    $("#addBtn").attr("data",2);
    $("#addBtn").attr("data-target","#myModal_2");
}


function zTreeOnClick(event, treeId, treeNode) {
    console.log(treeNode);
    $.ajax({
        type : "get",
        url : ctx+"/getZkNodeData",
        async : false,//同步请求
        data:{clusterId:treeNode.clusterId,path:treeNode.name},
        dataType:"text",
        success : function(val){
            $("#path2").val(treeNode.name);
            $("#pathVal2").val(val);
            $("#flag").val(treeNode.clusterId);
            $("#nextRow").show(800);
        },
        error:function(e){
            badMood("获取节点数据失败！");
        }
    });
};


function zTreeOnDblClick(event, treeId, treeNode) {
    getNodes(treeNode.clusterId);
    zTree.expandNode(treeNode, true, true, true);
};

function addZkNode(){
    var flag = $("#flag").val();
    if(flag==''){
        badMood("请先连接一个 ZK 集群再添加节点！");
    }else {
        var path = $("#path").val().trim();
        var pathVal = $("#pathVal").val().trim();
        if (path==''){
            badMood("路径为空！");
            $("#path").val("");
            $("#pathVal").val("");
        }else {
            $.ajax({
                type : "post",
                url : ctx+"/addZkNode",
                async : false,//同步请求
                data:{clusterId:flag,path:path,pathVal:pathVal},
                dataType:"text",
                success : function(){
                    getNodes(flag,null);
                    $("#path").val("");
                    $("#pathVal").val("");
                },
                error:function(e){
                    badMood("添加节点失败！可能的原因：节点已经存在！");
                }
            });
        }
    }
}
var zTree;

function getNodes(clusterId,who){
    $("#treeDemo").html("");
    $.ajax({
        type : "get",
        url : ctx+"/data",
        async : false,//同步请求
        data:{clusterId:clusterId},
        dataType:"json",
        success : function(json){
            $.fn.zTree.destroy("treeDemo");
            zNodes = json;
            zTreeObj = $.fn.zTree.init($("#treeDemo"), setting, zNodes);
            zTree = zTreeObj;
            /*$("#delAllNode").show(500);
            if (who==null){
            }else {
                $("button[data='flag']").each(function(){
                    $(this).removeClass("btn-success");
                });
                $(who).addClass("btn-success");
                $("#flag").val(clusterId);
            }*/
        },
        error:function(e){
            badMood("连接失败！");
            //$("#delAllNode").hide(500);
        }
    });
}

function clearConn(){
    $.ajax({
        type : "get",
        url : ctx+"/clearConn",
        async : false,//同步请求
        dataType:"text",
        success : function(){
            $("#treeDemo").html("");
            $("#delAllNode").hide(500);
            goodMood("连接已清空，请重新连接 ZK 服务！");
        },
        error:function(e){
            badMood("清空连接操作失败！");
        }
    });
}

function delAllNode(){
    layer.confirm('确定删除所有节点?', {icon: 3, title:'再次确认！'}, function(index){
        //确定
        var flag = $("#flag").val();
        $.ajax({
            type : "get",
            url : ctx+"/delAllNode",
            async : false,//同步请求
            data:{clusterId:flag},
            dataType:"text",
            success : function(){
                getNodes(flag,null);
            },
            error:function(e){
                badMood("删除所有节点失败！");
                getNodes(flag,null);
            }
        });
        layer.close(index);
    },function(index){
        //取消
        layer.close(index);
    });
}


function delZkNode(){
    var flag = $("#flag").val();
    var path = $("#path2").val();
    $.ajax({
        type : "post",
        url : ctx+"/delZkNode",
        async : false,//同步请求
        data:{clusterId:flag,path:path},
        dataType:"text",
        success : function(){
            $("#nextRow").hide(800);
            getNodes(flag,null);
        },
        error:function(e){
            badMood("删除节点失败！");
        }
    });
}


function removeReadonly(who){
    $(who).removeAttr("readonly");
}

function addReadonly(who){
    var flag = $("#flag").val();
    var path = $("#path2").val();
    var pathVal = $("#pathVal2").val();
    $.ajax({
        type : "post",
        url : ctx+"/updateZkNode",
        async : false,//同步请求
        data:{clusterId:flag,path:path,pathVal:pathVal},
        dataType:"text",
        success : function(){
        },
        error:function(e){
            badMood("更新节点数据失败！");
        }
    });
    $(who).attr("readonly","true");
}

